package server.lunch;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import server.dao.OrderDao;
import server.enitity.Order;
import server.server.OrderService;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName AppLunch
 * @Description
 * @Author Jingxiao.Ye
 * @Date 2021/12/19 下午11:53
 * @Version V1.0
 * @Since JDK 11
 */
@Component
public class AppLunch implements ApplicationRunner {

    @Autowired
    private OrderService orderService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        insertOrder();
    }

    public void insertOrder() {
//        按自己设计的表结构，插入 100 万订单模拟数据，测试不同方式的插入效率
        //插入数据前删除索引，插入数据库后再添加索引
        //方案思考:1.数据转csv通过load data加载
        //2.通过mysql事物和批量插入进行批量提交
        //3.使用import table导入csv文件
        int count = 100_0000;
        List<Order> orders = buildOrderList(count);
        System.out.println("start:" + System.currentTimeMillis());
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        for (int i = 0; i < count/500; i++) {
            List<Order> orders1 = orders.subList(i * 500, (i+1) * 500);
            executorService.execute(()->{
                orderService.batchOrder(orders1);
            });
        }
        System.out.println("end:" + System.currentTimeMillis());
    }

    public static List<Order> buildOrderList(int num) {
        List<Order> list = new ArrayList<>(num);
        Random random = new Random();
        Date date = new Date();
        for (int i = 0; i < num; i++) {
            Order order = new Order();
            //id可以通过雪花算法生成
            order.setId(i + 1);
            order.setUserId(random.nextInt(1000000) + 1);
            order.setItemId(random.nextInt(10000) + 1);
            order.setCount(random.nextInt(10) + 1);
            BigDecimal bigDecimal = new BigDecimal(order.getItemId() * 10);
            order.setPrice(bigDecimal);
            order.setPriceSum(bigDecimal.multiply(BigDecimal.valueOf(order.getCount())));
            order.setCreateTime(date);
            order.setUpdateTime(date);
            order.setOrderNo("WX_" + date.getTime() + "_" + order.getId());
            order.setBussinessId("123456");
            order.setStatus((short) 1);
            order.setItemName("A");
            list.add(order);
        }
        return list;
    }
}
